/*
 * Assignment05a.c
 *
 * Created: 4/17/2015 8:08:25 PM
 *  Author: Jeevake Attapattu
 */ 

#define F_CPU 8000000UL //XTAL = 8MHZ
#include <avr/io.h>
#include <util/delay.h>
#define ENABLE 1


int ReadADC(uint16_t ADCchannel)
{
	int ADCval;
	ADMUX = (ADMUX & 0xF0)|(ADCchannel & 0x0F);//select channel
	ADCSRA |= 1<<ADSC;//start conversion
	while(ADCSRA & (1<<ADSC));//wait for conversion
	ADCval = ADC>>6;//use only upper 10 bits of 16 bits
	ADCSRA 	|= 	1<<ADSC;
	return ADCval;
}



int main()
{
	ADMUX = (1<<REFS0)|(1<<ADLAR);//set Vref to 5V and left justify
	ADCSRA =(1<<ADIE)|(1<<ADEN);//set prescalar to 2, enable ADC interrupt and enable ADC
	ADCSRB = 0x00;//set ADC constant conversion
	int delay = ReadADC(0);//read ADC channel 0 POTENTIOMETER
	DDRB = 0xFF; //make PORTB output
	
	while(1)
	{
		//increased on time increases the average power
		delay = ReadADC(0);
		PORTB = PORTB | (1<<ENABLE);	//turn off
		_delay_ms(10);
		PORTB = PORTB & (~(1<<ENABLE)); // turn on
		for (int j = 0; j<delay; j+=10)
			_delay_ms(10);						
	}
	return 0 ;
}